package cn.yuanqiao.auth.service;


import cn.yuanqiao.auth.util.TokenParamUtil;
import cn.yuanqiao.common.exception.ServiceException;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: ApiRequestService
 * @Description: 类的描述
 * @author: lihuahua
 * @date: 2023/11/20 14:40
 * @Blog: huahuacoco.top
 */

@Service
public class ApiRequestService {

    public Map<String,Object> getAccessToken(String code) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        if (!StringUtils.isEmpty(TokenParamUtil.getClientId()) && !StringUtils.isEmpty(TokenParamUtil.getClientSecret())) {
            StringBuffer basicToken = new StringBuffer("Basic ");
            basicToken.append(Base64.getEncoder().encodeToString((TokenParamUtil.getClientId() + ":" + TokenParamUtil.getClientSecret()).getBytes()));
            MultiValueMap<String, String> formData = new LinkedMultiValueMap();
            formData.add("grant_type", "authorization_code");
            formData.add("code", code);
            formData.add("redirect_uri", TokenParamUtil.getRedirectPath());
            formData.add("client_id", TokenParamUtil.getClientId());
            formData.add("client_secret", TokenParamUtil.getClientSecret());
            /*RestTemplate client = new RestTemplate();*/
            RestTemplate client = null;

            client = new RestTemplate(ApiRestTemplateConfig.generateHttpRequestFactory());

            HttpHeaders headers = new HttpHeaders();
            HttpMethod method = HttpMethod.POST;
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.set("Authorization", basicToken.toString());
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity(formData, headers);

            ResponseEntity<Map> response = null;

            response = client.exchange(TokenParamUtil.getOAuthPath()+"/idp/oauth2/getToken", method, requestEntity, Map.class, new Object[0]);
            Map<String,Object> result = (Map) response.getBody();

            HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

            return result;
        } else {
            return null;
        }
    }

    public Map<String,Object> getUserInfo(String accessToken,String uid) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        if (!StringUtils.isEmpty(TokenParamUtil.getClientId()) && !StringUtils.isEmpty(TokenParamUtil.getClientSecret())) {
            //body的form参数
            MultiValueMap<String, String> formData = new LinkedMultiValueMap();

            //url的参数
            MultiValueMap<String, String> uriVariables = new LinkedMultiValueMap();

            RestTemplate client = null;

            client = new RestTemplate(ApiRestTemplateConfig.generateHttpRequestFactory());

            //header的参数
            HttpHeaders headers = new HttpHeaders();
            HttpMethod method = HttpMethod.GET;
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity(formData, headers);

            ResponseEntity<Map> response = null;

            response = client.exchange(
                    TokenParamUtil.getOAuthPath()+"/idp/oauth2/getUserInfo?access_token="+accessToken+"&client_id=" +
                            TokenParamUtil.getClientId() + "&uid="+uid
                    , method, requestEntity, Map.class, uriVariables);
            Map<String,Object> result = (Map<String,Object>) response.getBody();

            HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

            return result;
        } else {
            return null;
        }
    }

    public Map<String,Object> unifyIdentityManageRequest(String methodName,String tokenId,String taskId,Long guid,Boolean success,String message) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException,ServiceException {
        if (!StringUtils.isEmpty(TokenParamUtil.getClientId()) && !StringUtils.isEmpty(TokenParamUtil.getClientSecret())) {
            MultiValueMap<String, Object> formData = new LinkedMultiValueMap();

            Map<String, Object> requestDataMap = new HashMap<>();
            if ("login".equals(methodName)) {
                requestDataMap.put("systemCode", TokenParamUtil.getSystemCode());
                requestDataMap.put("integrationKey", TokenParamUtil.getIntegrationKey());
                requestDataMap.put("force","true");
            }else if ("pullTask".equals(methodName)||"logout".equals(methodName)){
                requestDataMap.put("tokenId",tokenId);
            }else if ("pullFinish".equals(methodName)) {
                requestDataMap.put("tokenId",tokenId);
                requestDataMap.put("taskId", taskId);
                requestDataMap.put("guid", guid);
                requestDataMap.put("success", success);
                requestDataMap.put("message", message);
            }
            requestDataMap.put("timestamp",System.currentTimeMillis());
            String jsonRequest = JSONObject.toJSONString(requestDataMap);

            RestTemplate client = new RestTemplate(ApiRestTemplateConfig.generateHttpRequestFactory());

            HttpHeaders headers = new HttpHeaders();
            HttpMethod method = HttpMethod.GET;
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.set("consumerCode", TokenParamUtil.getConsumerCode());
            headers.set("operationCode", "cn.crec.group.sso.integration.api.jsonV2");

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity(formData, headers);

            ResponseEntity<Map> response = client.exchange(TokenParamUtil.getIdentityManagePath()+
                            "/cn.crec.group.sso.integration.api.jsonV2?method={methodName}&request={jsonRequest}"
                    , method, requestEntity, Map.class,methodName, jsonRequest);
            Map<String,Object> result = (Map<String,Object>) response.getBody();

            HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            if (!"".equals(result.get("message"))){

                throw new ServiceException("请求统一身份管理接口"+methodName+"方法失败："+result.get("message"));
            }

            return (Map<String, Object>) result.get("data");
        } else {
            return null;
        }
    }

    public void checkResultMapIsQualified(Map<String,Object> map,String emptyMsg) throws ServiceException {
        if (map==null){
            throw new ServiceException(emptyMsg);
        }
        if (map.get("errcode")!=null){
            throw new ServiceException("错误代码"+map.get("errcode")+","+map.get("msg"));
        }
    }

}
